package com.wootion.cims.module.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wootion.cims.dao.*;
import com.wootion.cims.module.communityresidence.residencelist.model.Residence;
import com.wootion.cims.module.map.dto.Condition;
import com.wootion.cims.module.map.service.HousingMapService;
import com.wootion.cims.module.systemsetting.polt.model.SysPlot;
import com.wootion.cims.module.systemsetting.user.model.SysUserRole;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import com.wootion.cims.shiro.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: LanQiang
 * @Date: 2023/01/05/13:59
 * @Description: 住房统计
 */
@Slf4j
@Service
public class HousingMapServiceImpl implements HousingMapService {
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysUserCommunityDao sysUserCommunityDao;
    @Resource
    private SysPlotDao sysPlotDao;
    /**
     * 统计住房
     * @param condition
     * @return
     */
    @Override
    public ResponseResult statistics(Condition condition) {
        //获取当前登陆人的信息
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(SysUserRole::getUserId, user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(lambdaQueryWrapper5);
        String roleKey = sysRoleDao.findByRoles(sysUserRole.getRoleId());
        String communityId = null;
        String plotId = null;
        if(!Objects.isNull(condition)){
            communityId = condition.getCommunityId();//社区id
            plotId = condition.getPlotId();//小区id
        }
        List<SysPlot> sysPlots = null;
        //如果是街道管理员
        if ("street:admin".equals(roleKey)) {
            sysPlots = sysPlotDao.countHouseholdsAvailable(null, communityId, plotId);
        }else{
            //如果不是街道管理员
            List<String> commnityIds = sysUserCommunityDao.commnityIds(user.getId());
            if (Objects.isNull(commnityIds) || commnityIds.size() <= 0) {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户还没有任何社区权限").build();
            }
            sysPlots = sysPlotDao.countHouseholdsAvailable(commnityIds, communityId, plotId);
        }

        JSONObject jsonObject = new JSONObject();
        //应住户数
        int householdAvailable = 0;
        //当前用户能查看到的所有小区的id
        List<String> plotIds = new ArrayList<>();
        if(sysPlots != null &&  sysPlots.size()>0){
            for (SysPlot sysPlot : sysPlots) {
                if(sysPlot.getHouseholdsAvailable() != null){
                    householdAvailable += sysPlot.getHouseholdsAvailable();
                }
                plotIds.add(sysPlot.getId());
            }
        }

        //应住户数统计完毕
        jsonObject.put("householdAvailable",householdAvailable);
        
        //住宅总数查询
        List<Residence> residenceList = null;
        if(plotIds.size()>0){
            residenceList = sysPlotDao.typeMapCount(plotIds);
        }

        //统计住宅类别
        Map<String,Object> typeMap = new HashMap<>();
        //住宅总数
        if(residenceList != null){
            typeMap.put("typeMapCount",residenceList.size());
        }else {
            typeMap.put("typeMapCount",0);
        }

        int a = 0;//自有住房
        int b = 0;//公有住房
        int c = 0;//公租房
        if(residenceList != null && residenceList.size()>0){
            for (Residence residence : residenceList) {
                if(residence.getClasses().equals("自有住宅")){
                    a++;
                }else if (residence.getClasses().equals("公有住宅")){
                    b++;
                }else{
                    c++;
                }
            }
            typeMap.put("own_count",a);//自有住房
            typeMap.put("pub_count",b);//公有住房
            typeMap.put("ten_count",c);//公租房
            jsonObject.put("residenceType",typeMap);


            //实住户数，已经入住的住宅
            if(plotIds.size()>0){
                List<Residence> residences = sysPlotDao.countOccupancy(plotIds);
                List<String> abodeIds = new ArrayList<>();
                if(residences != null){
                    jsonObject.put("occupancyAvailable",residences.size());
                    for (Residence residence : residences) {
                        abodeIds.add(residence.getId());
                    }
                }else {
                    jsonObject.put("occupancyAvailable",0);
                }

                //租户住房数,统计租户的住房数
                if(abodeIds.size()>0){
                    List<Map<String, Object>> maps = sysPlotDao.countTenant(abodeIds);
                    if(maps != null && maps.size()>0){
                        jsonObject.put("tenantCount",maps.size());
                    }else{
                        jsonObject.put("tenantCount",0);
                    }
                }else {
                    jsonObject.put("tenantCount",0);
                }


                //空房数，建立房子，但是没有人住
                //获取住宅的总数
                int count = (int) typeMap.get("typeMapCount");
                
                int occupancyAvailable = (int) jsonObject.get("occupancyAvailable");

                jsonObject.put("vacantRoom",count - occupancyAvailable);
                
                //租户住房比例
                Map<String,Object> typeMap2 = new HashMap<>();

                //租户住房数
                int tenantCount = (int) jsonObject.get("tenantCount");
                typeMap2.put("tenantCount",tenantCount);
                //非租户住房数

                typeMap2.put("notTenantCount",count - tenantCount);
                
                //住宅总数
                Map<String,Object> residenceType = (Map<String, Object>) jsonObject.get("residenceType");
                int mapCount = (int) residenceType.get("typeMapCount");
                typeMap2.put("typeMapCount",residenceList.size());
                jsonObject.put("tenantMap",typeMap2);



                //空房比例
                Map<String,Object> typeMap3 = new HashMap<>();
                //住宅总数
                typeMap3.put("typeMapCount",residenceList.size());
                int vacantRoom = (int) jsonObject.get("vacantRoom");//空房数
                //空房数
                typeMap3.put("vacantRoom",vacantRoom);

                int notVacantRoom = mapCount-vacantRoom;
                typeMap3.put("notVacantRoom",notVacantRoom);
                jsonObject.put("vacancyRatio",typeMap3);
                return ResponseResult.builder().data(jsonObject).build();

            }else {
                jsonObject.put("occupancyAvailable",0);
                //租户住房数,统计租户的住房数
                jsonObject.put("tenantCount",0);
                //空房数，建立房子，但是没有人住
                jsonObject.put("vacantRoom",0);
                //租户住房比例
                Map<String,Object> typeMap2 = new HashMap<>();
                //租户住房数
                int tenantCount = (int) jsonObject.get("tenantCount");
                typeMap2.put("tenantCount",tenantCount);
                //非租户住房数
                typeMap2.put("notTenantCount",0);
                //住宅总数
                Map<String,Object> residenceType = (Map<String, Object>) jsonObject.get("residenceType");
                int mapCount = (int) residenceType.get("typeMapCount");
                typeMap2.put("typeMapCount",residenceList.size());
                jsonObject.put("tenantMap",typeMap2);



                //空房比例
                Map<String,Object> typeMap3 = new HashMap<>();
                //住宅总数
                typeMap3.put("typeMapCount",residenceList.size());
                int vacantRoom = (int) jsonObject.get("vacantRoom");//空房数
                //空房数
                typeMap3.put("vacantRoom",vacantRoom);

                int notVacantRoom = mapCount-vacantRoom;
                typeMap3.put("notVacantRoom",notVacantRoom);
                jsonObject.put("vacancyRatio",typeMap3);
                return ResponseResult.builder().data(jsonObject).build();
                
            }
        }else {
            typeMap.put("own_count",a);//自有住房
            typeMap.put("pub_count",b);//公有住房
            typeMap.put("ten_count",c);//公租房
            jsonObject.put("residenceType",typeMap);

            //实住户数，已经入住的住宅

            jsonObject.put("occupancyAvailable",0);

            //租户住房数,统计租户的住房数
            jsonObject.put("tenantCount",0);
            //空房数，建立房子，但是没有人住
            jsonObject.put("vacantRoom",0);


            //租户住房比例
            Map<String,Object> typeMap2 = new HashMap<>();

            //租户住房数
            int tenantCount = (int) jsonObject.get("tenantCount");
            typeMap2.put("tenantCount",tenantCount);
            //非租户住房数
            typeMap2.put("notTenantCount",0);
            //住宅总数
            Map<String,Object> residenceType = (Map<String, Object>) jsonObject.get("residenceType");
            int mapCount = (int) residenceType.get("typeMapCount");
            typeMap2.put("typeMapCount",0);
            jsonObject.put("tenantMap",typeMap2);



            //空房比例
            Map<String,Object> typeMap3 = new HashMap<>();
            //住宅总数
            typeMap3.put("typeMapCount",0);
            int vacantRoom = (int) jsonObject.get("vacantRoom");//空房数
            //空房数
            typeMap3.put("vacantRoom",vacantRoom);

            int notVacantRoom = mapCount-vacantRoom;
            typeMap3.put("notVacantRoom",notVacantRoom);
            jsonObject.put("vacancyRatio",typeMap3);
            return ResponseResult.builder().data(jsonObject).build();
        }

    }
}
